package com.yzf.demo.demo.Thread.lock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * Created by 于占峰 on 2020/4/4/004.
 * countdownlatch是一个同步工具类,它允许一个或多个线程一直等待,知道其他线程的操作执行完毕在执行.
 */
public class CountDownLatchDemo {


    public static void main(String[] args) throws InterruptedException {
        //传入3 代表三个线程执行后唤醒 --如果不在下面三个线程中countDownLatch.countDown(); 主线程会一直被阻塞
        CountDownLatch countDownLatch = new CountDownLatch(3);
        new Thread(() -> {
            countDownLatch.countDown();//倒计时 --3-1
            System.out.println(Thread.currentThread().getName());
        }).start();
        new Thread(() -> {
            countDownLatch.countDown();//倒计时 --2-1
            System.out.println(Thread.currentThread().getName());
        }).start();
//        new Thread(()->{
//            countDownLatch.countDown();//倒计时--1-1
//            System.out.println(Thread.currentThread().getName());
//            }).start();
        //countDownLatch.await();//阻塞主线程
        countDownLatch.await(10L, TimeUnit.SECONDS); //避免执行的线程数不够 导致所有线程一直在阻塞 可以传入超时时间
        System.out.println("主线程执行完毕");
    }

}
